<template>
  <div class="card">
    <div class="card-header">
      <div class="card-header-title">
        <span>任务列表</span>
      </div>
      <div class="card-header-toolbar">
        <a-input-search
          v-model:value="searchText"
          placeholder="搜索任务"
          style="width: 200px; margin-right: 16px"
          @search="handleSearch"
        />
        <a-select
          v-model:value="where.completed"
          style="width: 120px; margin-right: 16px"
          @change="handleSearch"
        >
          <a-select-option :value="null">全部任务</a-select-option>
          <a-select-option :value="false">未完成</a-select-option>
          <a-select-option :value="true">已完成</a-select-option>
        </a-select>
        <a-button style="margin-right: 16px" @click="handleReset">
          <template #icon><reload-outlined /></template>
          重置
        </a-button>
        <a-button type="primary" @click="showAddModal = true">
          <template #icon><plus-outlined /></template>
          添加任务
        </a-button>
      </div>
    </div>

    <div class="card-body">
      <a-spin :spinning="loading">
        <div class="task-list">
          <a-empty v-if="tasks.length === 0" />
          <div v-else class="task-grid">
            <a-card
              v-for="item in tasks"
              :key="item.taskId"
              class="task-card"
              :class="{ 'task-completed': item.status === '已完成', 'task-pinned': item.pinned === 'Y' }"
            >
                <div class="task-content">
                  <div class="task-header">
                    <a-checkbox
                      :checked="item.status === '已完成'"
                      @change="(e) => handleTaskComplete(item, e.target.checked)"
                    />
                    <span class="task-title" :class="{ 'text-completed': item.status === '已完成' }">
                      {{ item.title }}
                    </span>
                  </div>
                  <div class="task-info">
                    <span class="task-description">{{ item.description }}</span>
                    <div class="task-meta">
                      <span class="task-deadline">
                        <clock-circle-outlined />
                        截止时间：{{ item.dueDate }}
                      </span>
                    </div>
                  </div>
                  <div class="task-meta-row">
                    <a-tag :color="getPriorityColor(item.priority)">
                      {{ getPriorityText(item.priority) }}
                    </a-tag>
                    <div class="task-actions">
                      <a-button type="link" size="small" @click="handleEdit(item)">
                        <template #icon><edit-outlined /></template>
                      </a-button>
                      <a-button type="link" size="small" @click="handleDelete(item)">
                        <template #icon><delete-outlined /></template>
                      </a-button>
                      <a-button type="link" size="small" @click="handlePinned(item)">
                        <template #icon><pushpin-outlined /></template>
                      </a-button>
                    </div>
                  </div>
                </div>
            </a-card>
          </div>
          <div class="pagination-container">
            <div class="pagination-info">
              共 {{ total }} 条数据
            </div>
            <a-pagination
              :current="pageNo"
              :pageSize="pageSize"
              :total="total"
              :show-size-changer="true"
              :show-quick-jumper="true"
              :page-size-options="['9', '18', '27', '36']"
              @change="handlePageChange"
              @showSizeChange="handleSizeChange"
            />
          </div>
        </div>
      </a-spin>
    </div>

    <a-modal
      v-model:visible="showAddModal"
      :title="isEdit ? '修改任务' : '添加任务'"
      @ok="isEdit ? handleEditSubmit() : handleAddTask()"
      :confirm-loading="addLoading"
    >
      <a-form :model="taskForm" :rules="rules" ref="formRef">
        <a-form-item label="任务标题" name="title">
          <a-input v-model:value="taskForm.title" placeholder="请输入任务标题" />
        </a-form-item>
        <a-form-item label="任务描述" name="description">
          <a-textarea v-model:value="taskForm.description" placeholder="请输入任务描述" />
        </a-form-item>
        <a-form-item label="截止时间" name="dueDate">
          <a-date-picker
            v-model:value="taskForm.dueDate"
            show-time
            format="YYYY-MM-DD HH:mm"
            placeholder="请选择截止时间"
          />
        </a-form-item>
        <a-form-item label="优先级" name="priority">
          <a-select v-model:value="taskForm.priority" placeholder="请选择优先级">
            <a-select-option value="high">高</a-select-option>
            <a-select-option value="medium">中</a-select-option>
            <a-select-option value="low">低</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup name="TaskList">
import { ref, onMounted } from 'vue';
import { PlusOutlined, ClockCircleOutlined, ReloadOutlined, EditOutlined, DeleteOutlined, PushpinOutlined } from '@ant-design/icons-vue';
import { message, Modal } from 'ant-design-vue';
import dayjs from 'dayjs';
import { TasksApi } from '@/views/index/api/tasks';

const loading = ref(false);
const addLoading = ref(false);
const showAddModal = ref(false);
const formRef = ref();
const searchText = ref('');

const tasks = ref([]);
const total = ref(0);
const pageNo = ref(1);
const pageSize = ref(9);

const where = ref({
  searchText: '',
  pageNo: 1,
  pageSize: 9,
  sortField: 'createTime',
  sortOrder: 'desc',
  completed: false
});

const taskForm = ref({
  title: '',
  description: '',
  dueDate: null,
  priority: 'medium'
});

const rules = {
  title: [{ required: true, message: '请输入任务标题', trigger: 'blur' }],
  dueDate: [{ required: true, message: '请选择截止时间', trigger: 'change' }],
  priority: [{ required: true, message: '请选择优先级', trigger: 'change' }]
};

const isEdit = ref(false);
const currentTask = ref(null);

const getPriorityColor = (priority) => {
  const colors = {
    high: 'red',
    medium: 'orange',
    low: 'green'
  };
  return colors[priority] || 'blue';
};

const getPriorityText = (priority) => {
  const texts = {
    high: '高优先级',
    medium: '中优先级',
    low: '低优先级'
  };
  return texts[priority] || '未知';
};

const handleTaskComplete = async (task, completed) => {
  try {
    const submitData = {
      taskId: task.taskId,
      completed: completed
    };
    console.log('更新任务状态：', submitData);
    await TasksApi.updateTaskStatus(submitData);
    task.status = completed ? '已完成' : '未完成';
    message.success(completed ? '任务已完成' : '任务已取消完成');
  } catch (error) {
    console.error('更新任务状态失败', error);
    message.error('更新任务状态失败：' + (error.message || '未知错误'));
  }
};

const handleEdit = (task) => {
  isEdit.value = true;
  currentTask.value = task;
  taskForm.value = {
    title: task.title,
    description: task.description || '',
    dueDate: dayjs(task.dueDate),
    priority: task.priority
  };
  showAddModal.value = true;
};

const handleEditSubmit = () => {
  formRef.value.validate().then(async () => {
    try {
      addLoading.value = true;
      const submitData = {
        ...taskForm.value,
        taskId: currentTask.value.taskId,
        dueDate: dayjs(taskForm.value.dueDate).format('YYYY-MM-DD HH:mm'),
        status: currentTask.value.status
      };
      console.log('提交编辑数据：', submitData);
      await TasksApi.updateTask(submitData);
      message.success('修改成功');
      showAddModal.value = false;
      resetForm();
      await getTaskList();
    } catch (error) {
      console.error('修改失败', error);
      message.error('修改失败：' + (error.message || '未知错误'));
    } finally {
      addLoading.value = false;
    }
  }).catch(error => {
    console.error('表单验证失败', error);
    message.error('请填写必填项');
  });
};

const handlePinned = async (task) => {
  try {
    const submitData = {
      taskId: task.taskId,
      pinned: task.pinned === 'Y' ? 'N' : 'Y'
    };
    const response = await TasksApi.updateTaskPinned(submitData);
    if (response?.success) {
      task.pinned = submitData.pinned;
      message.success(task.pinned === 'Y' ? '任务已置顶' : '任务已取消置顶');
      await getTaskList();
    }
  } catch (error) {
    console.error('更新任务置顶状态失败', error);
    message.error(error?.message || '操作失败');
  }
};

const handleDelete = (task) => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这个任务吗？',
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        const submitData = {
          taskId: task.taskId
        };
        console.log('删除任务：', submitData);
        await TasksApi.deleteTask(submitData);
        message.success('删除成功');
        await getTaskList();
      } catch (error) {
        console.error('删除失败', error);
        message.error('删除失败：' + (error.message || '未知错误'));
      }
    }
  });
};

const resetForm = () => {
  taskForm.value = {
    title: '',
    description: '',
    dueDate: null,
    priority: 'medium'
  };
  isEdit.value = false;
  currentTask.value = null;
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

const handleAddTask = () => {
  formRef.value.validate().then(async () => {
    try {
      addLoading.value = true;
      const submitData = {
        ...taskForm.value,
        dueDate: dayjs(taskForm.value.dueDate).format('YYYY-MM-DD HH:mm')
      };
      await TasksApi.addTask(submitData);
      message.success('添加成功');
      showAddModal.value = false;
      resetForm();
      await getTaskList();
    } catch (error) {
      message.error('添加失败');
    } finally {
      addLoading.value = false;
    }
  });
};

const handleSearch = () => {
  where.value.pageNo = 1;
  getTaskList();
};

const handleReset = () => {
  where.value.searchText = '';
  where.value.pageNo = 1;
  where.value.pageSize = 9;
  where.value.completed = false;
  getTaskList();
};

const getTaskList = async () => {
  try {
    loading.value = true;
    const response = await TasksApi.getTasksPage({
      ...where.value,
      searchText: where.value.searchText || ''
    });
    if (response) {
      tasks.value = response.rows || [];
      total.value = response.totalRows || 0;
      pageNo.value = response.pageNo || 1;
      pageSize.value = response.pageSize || 9;
    } else {
      tasks.value = [];
      total.value = 0;
      message.warning('暂无任务数据');
    }
  } catch (error) {
    message.error('获取任务列表失败');
    tasks.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

const handlePageChange = (page, size) => {
  where.value.pageNo = page;
  where.value.pageSize = size;
  getTaskList();
};

const handleSizeChange = (current, size) => {
  where.value.pageNo = 1;
  where.value.pageSize = size;
  getTaskList();
};

onMounted(() => {
  getTaskList();
});
</script>

<style scoped lang="less">
.card {
  width: 100%;
  height: 100%;
  background-color: white;
  box-shadow: 0 0 6px hsla(0, 0%, 80%, 0.5);
  border-radius: 4px;
  padding: 10px;
  
  @media (max-width: 768px) {
    padding: 8px;
  }
}

.card-header {
  width: 100%;
  min-height: 50px;
  border-bottom: 1px #999999 solid;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 8px;
  
  @media (max-width: 768px) {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
    padding-bottom: 12px;
  }
}

.card-header-title {
  font-size: 18px;
  font-weight: 500;
  
  @media (max-width: 768px) {
    font-size: 16px;
  }
}

.card-header-toolbar {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
  
  @media (max-width: 768px) {
    flex-direction: column;
    gap: 8px;
    width: 100%;
  }
}

.search-input {
  width: 200px;
  
  @media (max-width: 768px) {
    width: 100%;
  }
}

.status-select {
  width: 120px;
  
  @media (max-width: 768px) {
    width: 100%;
  }
}

.reset-btn, .add-btn {
  @media (max-width: 768px) {
    width: 100%;
  }
}

.btn-text {
  @media (max-width: 768px) {
    display: inline;
  }
}

.card-body {
  width: 100%;
  height: calc(100% - 50px);
  overflow-y: auto;
  padding: 10px;
  
  @media (max-width: 768px) {
    height: calc(100% - 120px);
    padding: 8px;
  }
}

.task-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-bottom: 16px;
  
  @media (max-width: 1024px) {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  
  @media (max-width: 768px) {
    grid-template-columns: 1fr;
    gap: 12px;
  }
}

.task-card {
  height: 100%;
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
  }
  
  @media (max-width: 768px) {
    &:hover {
      transform: none;
    }
  }
}

.task-content {
  width: 100%;
}

.task-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  
  @media (max-width: 768px) {
    gap: 6px;
  }
}

.task-title {
  font-size: 16px;
  font-weight: 500;
  flex: 1;
  word-break: break-word;
  
  @media (max-width: 768px) {
    font-size: 14px;
  }
}

.text-completed {
  text-decoration: line-through;
  color: #999;
}

.task-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.task-description {
  color: #666;
  word-break: break-word;
  line-height: 1.4;
  
  @media (max-width: 768px) {
    font-size: 13px;
  }
}

.task-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 8px 0;
  color: #999;
  font-size: 12px;
  
  @media (max-width: 768px) {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
}

.task-meta-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  @media (max-width: 768px) {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}

.task-deadline {
  display: flex;
  align-items: center;
  gap: 4px;
  
  @media (max-width: 768px) {
    font-size: 11px;
  }
}

.deadline-text {
  @media (max-width: 768px) {
    display: none;
  }
}

.task-completed {
  background-color: #f5f5f5;
}

.task-pinned {
  background-color: #fffbe6;
  border: 1px solid #ffe58f;
  .ant-card-body {
    padding: 15px;
    
    @media (max-width: 768px) {
      padding: 12px;
    }
  }
}

.task-actions {
  display: flex;
  gap: 4px;
  
  @media (max-width: 768px) {
    gap: 8px;
  }
}

.task-actions .ant-btn {
  padding: 0 4px;
  
  @media (max-width: 768px) {
    padding: 4px 8px;
    min-width: 32px;
  }
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  padding: 16px 0;
  
  @media (max-width: 768px) {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
}

.pagination-info {
  color: rgba(0, 0, 0, 0.45);
  font-size: 14px;
  
  @media (max-width: 768px) {
    text-align: center;
    font-size: 12px;
  }
}

.task-modal {
  @media (max-width: 768px) {
    .ant-modal {
      margin: 16px;
      max-width: calc(100vw - 32px);
    }
  }
}
</style>